package com.project.finance.mobile.bill.controller;

import com.project.finance.common.po.TbBill;
import com.project.finance.common.resultconfig.Result;
import com.project.finance.common.resultconfig.ResultGenerator;
import com.project.finance.mobile.bill.service.BillService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Slf4j
@RestController

public class BillController {
    @Autowired
    private BillService billService;

    //记账
    @RequestMapping(value = "bill", method = RequestMethod.POST)
    public Result insert(TbBill tbBill) {
        log.info(String.valueOf(tbBill));
        int i = billService.insert(tbBill);
        if (i > 0) {
            return ResultGenerator.apiSuccess("记账成功");
        } else {
            return ResultGenerator.apiError("记账失败");
        }

    }

    //查询账单
    @RequestMapping(value = "bill", method = RequestMethod.GET)
    public Result listBill(@RequestParam("userId") int userId) {

        List<TbBill> tbBills = billService.listBill(userId);

        //收入Income
        Integer billIncome=billService.selectIncome(userId);

        log.info("收入-------"+billIncome);
        //支出expend
        Integer billExpend = billService.selectExpend(userId);
        log.info("支出**********"+billExpend);
        //余额
        Integer billBalance=billIncome-billExpend;
        log.info("余额-------"+billBalance);


        /*对数据进行组装*/
        HashMap<Object, Object> resultMap = new HashMap<>();
        ArrayList<HashMap<String,Object>> resultList = new ArrayList<>();

        resultMap.put("billIncome",billIncome);
        resultMap.put("billExpend",billExpend);
        resultMap.put("billBalance",billBalance);

        for (TbBill tbBill : tbBills) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("billId", tbBill.getBillId());
            map.put("billType", tbBill.getBillType());
            map.put("billAmount", tbBill.getBillAmount());
            map.put("billUse", tbBill.getBillUse());
            map.put("billRemark", tbBill.getBillRemark());
            map.put("billCreatedate", tbBill.getBillCreatedate());
            map.put("billUserId", tbBill.getBillUserId());
            resultList.add(map);
        }
        resultMap.put("billList", resultList);
        return ResultGenerator.apiSuccess(resultMap);
    }
}